package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.JianYangForumDownLoader;
import com.spider.silence.utils.PropertiesUtil;

import java.util.LinkedList;

/**
 * @author liyuanguo
 * @version V1.0
 * @time 2017/1/19 15:44
 * @description
 */
public class JianYangDownLoaderPool {
    private static JianYangDownLoaderPool  instance= new JianYangDownLoaderPool();;
    protected LinkedList<JianYangForumDownLoader> pool = Lists.newLinkedList();
    private JianYangDownLoaderPool(){
        for(int i = 0; i<Integer.valueOf(PropertiesUtil.getVal("JianYang.DownLoader.Pool.initNum")); i++){
            JianYangForumDownLoader downLoader =new JianYangForumDownLoader();
            downLoader.init();
            pool.add(downLoader);
        }
    };
    public  static JianYangDownLoaderPool getInstance(){
        return  instance;
    }
    public  void releaseDownLoader(JianYangForumDownLoader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }
    public  JianYangForumDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                JianYangForumDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }

    /**
     * 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }
}
